<?php

class GalleriesController extends AppController {
	
	var $name = 'Galleries';
	var $uses = array('Gallery', 'GalleryImage');
	var $helpers = array('Js' => array('Jquery'), 'Html'); 
	
	
	function index() {
		
		$user = $this->Session->read('user');
		$galleries = $this->Gallery->find('all', array('conditions'=>array('Gallery.user_id'=>$user['User']['id'])));
		$this->set('galleries', $galleries);
	}
	
	function view_gallery($id = null) {
		$user = $this->Session->read('user');
		
		$this->Gallery->id = $id;
		$gallery = $this->Gallery->read();
		$this->set('gallery', $gallery);
			
		$images = $this->GalleryImage->find('all', array('conditions'=>array('GalleryImage.gallery_id'=>$id)));
		$this->Set('images', $images);
		$this->log($images, 'debug');
	}
	
	function add_gallery() {
		if (!empty($this->data)) {

			$user = $this->Session->read('user');
			$this->Gallery->set('user_id', $user['User']['id']);
			
			//If the form data can be validated and saved...        
			if($this->Gallery->save($this->data)) {
				
				$gallery = $this->Gallery->find('first', array(
                                              'conditions' => array('Gallery.name' => $this->data['Gallery']['name'])));
				//Moving and renaming the image uploaded
				if($this->data['Gallery']['image']['tmp_name']){
					$target_path = 'img/gallery/'.$gallery['Gallery']['id'].'.jpg';
					move_uploaded_file($this->data['Gallery']['image']['tmp_name'], $target_path);
				}

				$this->Session->setFlash('You have created a new photo gallery successfully.', 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));	
			}
		}
	}
	
	function add_images($gallery_id = null) {
		$this->Gallery->id = $gallery_id;
		$gallery = $this->Gallery->read();
		$this->set('gallery', $gallery);
		
		
		if (!empty($this->data)) {
			
			$this->GalleryImage->set('gallery_id', $gallery_id);
			$this->GalleryImage->set('name', $this->data['Gallery']['image']['name']);
			$this->GalleryImage->set('description', $this->data['Gallery']['description']);
			
			if($this->GalleryImage->save($this->data)) {
				
				$image = $this->GalleryImage->find('first', array(
                                              'conditions' => array('GalleryImage.name' => $this->data['Gallery']['image']['name'])));
					
				// Moving and renaming the image uploaded
				if($this->data['Gallery']['image']['tmp_name']){
					$target_folder = 'img/gallery/'.$gallery_id;
					if(!is_dir($target_folder))
						mkdir($target_folder);
					$target_path = $target_folder. '/'. $image['GalleryImage']['id'].'.jpg';
					move_uploaded_file($this->data['Gallery']['image']['tmp_name'], $target_path);
				}
				
				$this->redirect(array('action' => 'view_gallery', $gallery_id));
			}
		}
	}
}

?>